package com.sinodata.bsm.cicp.collector.sybase;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.constants.SeparatorConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class Session extends AbstractJDBCCollector {

    private static final Logger logger = Logger.getLogger(Session.class);

    /**
     * 采集方法
     * 
     * @param pParmeters
     *            Sybase Session资源的属性值数组: 会话列表
     * @return session,
     */

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {

        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();

        ResPropertyValue propertyValueX = new ResPropertyValue();
        try {
            String[] propMetas = getPropMeta();
            //        String serverName = this.getParamMap().get("服务器名");
            String serverName = this.getParamMap().get("ServerName");
            System.out.println("serverName:" + serverName);
            String sql = "SELECT spid, fid, status, isnull(SUSER_NAME(suid),'') suser, isnull(hostname,'') " + "hostname,isnull(program_name,'') program_name, memusage, cpu, physical_io, blocked," + "DB_NAME(dbid) dbname, cmd, isnull(tran_name,'') tran_name, isnull(time_blocked,0) time_blocked" + " FROM master.dbo.sysprocesses ORDER by 3";
            String[] rs = this.getStrings(serverName, sql, ip);
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
            for (int i = 0; i < propMetas.length; i++) {
                propValues[i] = ResPropertyValue.createPropValue(rs[i], propMetas[i]);
            }
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
        } catch (Exception ex) {
            logger.error("failed to collect sybase session", ex);
            throw new CollectorException(ex);
        }
        return values;
    }

    private String[] getStrings(String serverName, String sql, String ip) throws CollectorException {

        String[] propValArr = new String[1];
        try {

            ResultSet rst = this.getCachedResultSet("sybase", ip, serverName, sql);
            if (rst != null) {
                StringBuffer sessions = new StringBuffer("");
                //进程ID|父进程ID|状态|服务器用户名|主机名|程序名|内存占用量|积累CPU时间|当前命令的磁盘读写次数|阻塞的进程数|数据库名|命令行|活动的事务名称|阻塞时间(秒)
                //                sessions.append("Process ID").append(SeparatorConstants.COL_SEPARATOR);//进程ID
                //                sessions.append("Parent Process ID").append(SeparatorConstants.COL_SEPARATOR);//父进程ID
                //                sessions.append("Status").append(SeparatorConstants.COL_SEPARATOR);//状态
                //                sessions.append("Server User Name").append(SeparatorConstants.COL_SEPARATOR);//服务器用户名
                //                sessions.append("Host Name").append(SeparatorConstants.COL_SEPARATOR);//主机名
                //                sessions.append("Program Name").append(SeparatorConstants.COL_SEPARATOR);//程序名
                //                sessions.append("Memory Footprint").append(SeparatorConstants.COL_SEPARATOR);//内存占用量
                //                sessions.append("Cumulative CPU Time").append(SeparatorConstants.COL_SEPARATOR);//累积CPU时间
                //                sessions.append("The disk Reading and Writing Times").append(SeparatorConstants.COL_SEPARATOR);//当前命令的磁盘读写次数
                //                sessions.append("The number of Choked Process").append(SeparatorConstants.COL_SEPARATOR);//阻塞的进程数
                //                sessions.append("Database Name").append(SeparatorConstants.COL_SEPARATOR);//数据库名
                //                sessions.append("Command Line").append(SeparatorConstants.COL_SEPARATOR);//命令行
                //                sessions.append("Active Transaction Name").append(SeparatorConstants.COL_SEPARATOR);//活动的事务名称
                //                sessions.append("Choke Time(s)").append(SeparatorConstants.COL_SEPARATOR).append(SeparatorConstants.LIN_SEPARATOR);//阻塞时间(秒)
                while (rst.next()) {
                    String line = getTabLineStr(rst, 14);
                    sessions.append(line).append(SeparatorConstants.LIN_SEPARATOR);
                }
                String configureInfostr = sessions.toString();

                propValArr[0] = configureInfostr;
            } else {
                return null;
            }

        } catch (Exception ex) {
            logger.error("while connect database : ", ex);
            throw new CollectorException(ex);
        }

        return propValArr;
    }

    private String getTabLineStr(ResultSet rst, int colNum) throws CollectorException {
        StringBuffer tabLineStr = new StringBuffer();
        try {
            for (int i = 1; i <= colNum; i++) {
                String val = rst.getString(i);
                if (val == null || val.trim().length() == 0) {
                    val = " ";
                } else
                    val = val.trim();
                tabLineStr.append(val).append(SeparatorConstants.COL_SEPARATOR);
            }
        } catch (Exception e) {
            logger.error("failed to get TabLineStr", e);
            throw new CollectorException(e);
        }
        return tabLineStr.toString();
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "ServerName" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "会话列表" };
        return new String[] { "SessionList" };
    }
}
